# -*- coding:utf-8 -*-
# 定义程序中的常量和各个模块之间的数据共享
import os
import yaml

class GlobalConfig(object):
    """
    Config单例类实现:
        使用__new__方法确保单例模式
        提供get()和set()方法访问配置项
        自动持久化配置到yaml文件
        通过get_instance()方法获取单例实例
    """
    EXCEL_DIR_KEY = 'excelDir'
    EXPORT_DIR_KEY = 'exportDir'
    DELIMITER_KEY = 'delimiter'
    EXPORT_TYPE_KEY = 'exportType'
    _instance = None
    _initialized = False
    data = {}
    config_path = "config"
    conf_filename = "config.yaml"

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            self._initialized = True

    @classmethod
    def get_instance(cls):
        return cls()

    def load_config(self):
        # 检查配置文件是否存在
        config_path = os.path.join("config")
        # 获取yaml文件路径
        self.config_path = os.path.join(config_path, self.conf_filename)
        if not os.path.exists(self.config_path):
            # 配置文件不存在,创建配置文件
            cfg = open(self.config_path, 'w', encoding='utf-8')
            # 初始化配置文件 dict
            self._init_config()
            # 写入,然后关闭
            yaml.dump(self.data, cfg, default_flow_style=False)
            cfg.close()
        try:
            if os.path.exists(self.config_path):
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    self.data = yaml.safe_load(f) or {}
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            self.data = {}

    def get(self, key, default=None):
        return self.data.get(key, default)

    def set(self, key, value):
        self.data[key] = value
        self.save_config()

    def save_config(self):
        """
        配置的字典内容存入配置文件
        """
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                yaml.dump(
                    self.data,
                    f,
                    allow_unicode=True,
                    sort_keys=False,
                    default_flow_style=False
                )
        except Exception as e:
            print(f"保存配置文件失败: {e}")

    def _init_config(self):
        self.data[self.EXCEL_DIR_KEY] = "./"
        self.data[self.EXPORT_DIR_KEY] = "./"
        self.data[self.DELIMITER_KEY] = '_'
        self.data[self.EXPORT_TYPE_KEY] = ""